//
//  FirstViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/9.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "FirstViewController.h"
#import "DSRefreshHeaderView.h"
#import "DSLoadFooterView.h"
#import "ComperesNewsTableViewCell.h"
#import "CompereViewModel.h"
#import <RACEXTScope.h>
#import <ReactiveCocoa.h>
#import <MBProgressHUD.h>
#import <UIButton+AFNetworking.h>
#import "MyHomePageViewController.h"

@interface FirstViewController ()<UITableViewDelegate,UITableViewDataSource,DSRefreshHeaderViewDelegate,DSLoadFooterViewDelegate,CompereCellDelegate>
@property (nonatomic ,weak) IBOutlet UIView *navView;
@property (nonatomic ,weak) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) DSRefreshHeaderView *headerView;
@property (nonatomic ,strong) DSLoadFooterView *footerView;
@property (nonatomic ,strong) CompereViewModel *compereViewModel;
@property (nonatomic ,assign) NSInteger currentPage;



@end
static NSString *reuseIdentify = @"cell";

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    _compereViewModel = [CompereViewModel shareCompereViewModel];
    _currentPage = 1;
    
    @weakify(self);
    
    
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"reload" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self.tableView reloadData];
        [self.headerView dsRefreshScrollViewDataSourceDidFinishedLoading:_tableView];
        
    }];
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"allload" object:nil] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        _currentPage -=1;
        
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelText = @"已全部加载";
        [self.view addSubview:hud];
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        }];
        [self.footerView dsLoadScrollViewDataSourceDidFinishedLoading:_tableView];
        
        
    }];
    
    [_compereViewModel getCompereAtPage:1];
        
    
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    
    return self;
}
#pragma  mark setup after loading the view
- (void)setupUI{
    
    UINib *cellNib = [UINib nibWithNibName:@"ComperesNewsTableViewCell" bundle:nil];
    [_tableView registerNib:cellNib forCellReuseIdentifier:reuseIdentify];
    _tableView.backgroundColor = [UIColor clearColor];
    [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
    _tableView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _tableView.layer.shadowColor = [[UIColor redColor]CGColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _navView.layer.shadowColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    
    
    _navView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _navView.layer.shadowOpacity = .3;
    
    
    _headerView = [[DSRefreshHeaderView alloc] init];
    _headerView.delegate = self;
    _headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [_tableView addSubview:_headerView];
    
    NSLayoutConstraint *headerLeading = [NSLayoutConstraint constraintWithItem:_headerView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *headerTrailing = [NSLayoutConstraint constraintWithItem:_headerView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
    
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:_headerView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:34];
    NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:_headerView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_tableView attribute:NSLayoutAttributeTop multiplier:1 constant:-30];
    
    
    
    [_headerView addConstraint:height];
    
    
    [_tableView addConstraint:headerLeading];
    [_tableView addConstraint:headerTrailing];
    [_tableView addConstraint:top];
    
    _footerView = [[DSLoadFooterView alloc] initWithFrame:CGRectMake(0, MAX(_tableView.contentSize.height, _tableView.frame.size.height), 320, 60)];
    _footerView.translatesAutoresizingMaskIntoConstraints = NO;
    _footerView.hidden = YES;
    _footerView.delegate = self;
    [_tableView addSubview:_footerView];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark TableView


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ComperesNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentify];
    if (!cell) {
        cell = [[ComperesNewsTableViewCell alloc] init];
    }
    NSDictionary *dic = [_compereViewModel dictionaryAtIndexPath:indexPath];
    cell.nickNameLabel.text = [dic objectForKey:@"nickname"];
    cell.timeLabel.text = [dic objectForKey:@"createtime"];
    cell.newsLabel.text = [dic objectForKey:@"content"];
    cell.phoneString = [dic objectForKey:@"phone"];
    cell.username = [dic objectForKey:@"username"];
    
    [cell.avatarButtom setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[dic objectForKeyedSubscript:@"avatar"]] placeholderImage:[UIImage imageNamed:@"touxiang.jpg"]];
    
    cell.layer.shadowColor = [[UIColor redColor] CGColor];
    cell.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_compereViewModel numberOfTableView];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = tableView.frame.size.width-122;
   
    
    NSDictionary *dic = [_compereViewModel dictionaryAtIndexPath:indexPath];
    NSString *text = [dic objectForKey:@"content"];
    
    
    CGSize labelSize = [text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    

    return MAX(80, 54+labelSize.height);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}
#pragma mark ScrollView

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_headerView dsRefreshScrollViewDidScroll:scrollView];
    [_footerView dsLoadScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_headerView dsRefreshScrollViewDidEndDragging:scrollView];
    [_footerView dsLoadScrollViewDidEndDragging:scrollView];
}


#pragma mark DSRefreshHeaderView

- (BOOL)dsRefreshTableHeaderDataSourceIsLoading:(DSRefreshHeaderView *)headerView{
    return NO;
}

- (NSDate *)dsRefreshTableHeaderDataSourceLastUpdated:(DSRefreshHeaderView *)headerView{
    return [NSDate date];
}

- (void)dsRefreshTableHeaderDidTriggerRefesh:(DSRefreshHeaderView *)headerView{
    
    _currentPage =1;
    [_compereViewModel getCompereAtPage:1];
    
    
    
    
}

#pragma mark LoadFooterView

- (BOOL)dsLoadTableViewIsLoading:(DSLoadFooterView *)footerView{
    return NO;
}

- (void)dsLoadTableViewDidTriggedLoad:(DSLoadFooterView *)footerView{
    
    _currentPage += 1;
    [_compereViewModel getCompereAtPage:_currentPage];
    
    
}

#pragma mark comperecell delegate

- (void)callPhone:(NSString *)phoneNumber{
    
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNumber];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

- (void)viewUser:(NSString *)username{
    MyHomePageViewController *homeVC = [[MyHomePageViewController alloc] initWithNibName:NSStringFromClass([MyHomePageViewController class]) bundle:nil];
    [self presentViewController:homeVC animated:YES completion:nil];
}
@end
